﻿using System;
using System.Linq;
using System.Web.Mvc;
using amk.Models;
using amk.ViewModels;

namespace amk.Controllers{

  public class CadastroController : Controller{
    amkEntities entities;

    public CadastroController() {
      entities = new amkEntities();
    }

    private const int tamanhoPagina = 10;

    [HttpGet]
    public ViewResult Index(int? pagina){
      var cadastroIndexViewModel = new CadastroIndexViewModel(){
        totalCadastro = entities.CADASTRO.Count(),
        paginaAtual = pagina ?? 1,
        totalPaginas = (int)Math.Ceiling(1.0 * entities.CADASTRO.Count() / tamanhoPagina),
        Cadastro = entities.CADASTRO.OrderBy(c => c.DSC_NOME).Skip(((pagina ?? 1) - 1) * tamanhoPagina).Take(tamanhoPagina).ToList(),
      };

      return View(cadastroIndexViewModel);
    }

    [HttpPost]
    public ViewResult Index(FormCollection formCadastro, int? pagina){
      var nomeCadastro = formCadastro[("DSC_NOME")].ToString();
      var cadastroIndexViewModel = new CadastroIndexViewModel(){
        totalCadastro = entities.CADASTRO.Where(c => c.DSC_NOME.Contains(nomeCadastro)).OrderBy(c => c.DSC_NOME).ToList().Count(),
        paginaAtual = pagina ?? 1,
        totalPaginas = (int)Math.Ceiling(1.0 * entities.CADASTRO.Where(c => c.DSC_NOME.Contains(nomeCadastro)).Count() / tamanhoPagina),
        Cadastro = entities.CADASTRO.Where(f => f.DSC_NOME.Contains(nomeCadastro)).OrderBy(c => c.DSC_NOME).Skip(((pagina ?? 1) - 1) * tamanhoPagina).Take(tamanhoPagina).ToList(),
      };

      return View(cadastroIndexViewModel);
    }

    public ViewResult Detalhe(int id)
    {
      return View();
    }

    [HttpGet]
    public ViewResult Criar(){
      
      //populando DDLs
      this.ViewData["listaUF"] = new SelectList(entities.UF.OrderBy(u => u.SIG_UF).ToList(), "SEQ_UF", "SIG_UF");
      this.ViewData["listaAcademia"] = new SelectList(entities.ACADEMIA.OrderBy(a => a.NOM_ACADEMIA).ToList(), "SEQ_ACADEMIA", "NOM_ACADEMIA");
      this.ViewData["listaGraduacao"] = new SelectList(entities.GRADUACAO.OrderBy(g => g.SEQ_GRADUACAO).ToList(), "SEQ_GRADUACAO", "NOM_GRADUACAO");
      return View();
    } 

    [HttpPost] //form enviado
    public ActionResult Criar(FormCollection formCadastro){

      var novoCadastro = new CADASTRO();
      var novaGraduacao = new CADASTRO_GRADUACAO();

      //populando DDLs
      amkEntities entityCriar = new amkEntities();
      this.ViewData["listaUF"] = new SelectList(entityCriar.UF.OrderBy(u => u.SIG_UF).ToList(), "SEQ_UF", "SIG_UF");
      this.ViewData["listaAcademia"] = new SelectList(entityCriar.ACADEMIA.OrderBy(a => a.NOM_ACADEMIA).ToList(), "SEQ_ACADEMIA", "NOM_ACADEMIA");

      //recupera valor das DDLs
      UF uf = new UF { SEQ_UF = Int32.Parse(formCadastro["SEQ_UF"]) };
      ACADEMIA academia = new ACADEMIA { SEQ_ACADEMIA = Int32.Parse(formCadastro["SEQ_ACADEMIA"]) };

      //atualizando o model - entity
      TryUpdateModel(novoCadastro, new string[] {"DAT_CADASTRO", "DSC_NOME", "DAT_NASCIMENTO", "NUM_IDENTIDADE", "NUM_CPF", "DSC_ENDERECO",
        "NOM_BAIRRO", "NOM_CIDADE", "SEQ_UF", "NUM_CEP", "NUM_TELEFONE_CASA", "NUM_TELEFONE_CELULAR", "NUM_TELEFONE_TRABALHO",
        "NUM_TELEFONE_FAX", "DSC_EMAIL", "NOM_PAI", "NOM_MAE", "DSC_OBSERVACAO", "NOM_ARQUIVO_FOTO", "DSC_SITUACAO_CADASTRO", 
        "FLG_CADASTRO_CBK", "DSC_SITUACAO_CADASTRO_CBK", "DAT_CADASTRO_CBK", "FLG_CONTATO_ACADEMIA", "SEQ_ACADEMIA"}, formCadastro.ToValueProvider());

      TryUpdateModel(novaGraduacao, new string[] { "SEQ_CADASTRO", "SEQ_GRADUACAO", "DAT_GRADUACAO" }, formCadastro.ToValueProvider());

      //Atualiza valores das FKs
      entities.AttachTo("UF", uf);
      entities.AttachTo("ACADEMIA", academia);

      novoCadastro.UF = uf;
      novoCadastro.ACADEMIA = academia;

      if (ModelState.IsValid){
        entities.AddToCADASTRO(novoCadastro);
        entities.SaveChanges();
        return RedirectToAction("Index");
      }
      return View(novoCadastro);
    }

    [HttpGet]
    public ViewResult Editar(int id){
      var cadastro = entities.CADASTRO.FirstOrDefault(c => c.SEQ_CADASTRO == id);
      var cadastroEditarViewModel = new CadastroEditarViewModel() {
        Cadastro = cadastro,
        Academia = entities.ACADEMIA.OrderBy(a => a.NOM_ACADEMIA).ToList(),
        Graduacao =  entities.GRADUACAO.OrderBy(g => g.SEQ_GRADUACAO).ToList(),
        CadastroGraduacao = entities.CADASTRO_GRADUACAO.Where(cg => cg.SEQ_CADASTRO == id).ToList(),
        Uf = entities.UF.OrderBy(u => u.SIG_UF).ToList()
      };

      return View(cadastroEditarViewModel);
    }

    [HttpPost] //form enviado
    public ActionResult Editar(FormCollection formCadastro){

      //populando DDLs
      amkEntities entityEditar = new amkEntities();
      this.ViewData["listaUF"] = new SelectList(entityEditar.UF.OrderBy(u => u.SIG_UF).ToList(), "SEQ_UF", "SIG_UF");
      this.ViewData["listaAcademia"] = new SelectList(entityEditar.ACADEMIA.OrderBy(a => a.NOM_ACADEMIA).ToList(), "SEQ_ACADEMIA", "NOM_ACADEMIA");

      //recupera cadastro para alteração
      var cadastroId = Int32.Parse(formCadastro["SEQ_CADASTRO"]);
      var cadastro = entities.CADASTRO.First(c => c.SEQ_CADASTRO == cadastroId);
      
      //recupera valor das DDLs
      UF novaUF = new UF { SEQ_UF = Int32.Parse(formCadastro["SEQ_UF"]) };
      ACADEMIA novaAcademia = new ACADEMIA { SEQ_ACADEMIA = Int32.Parse(formCadastro["SEQ_ACADEMIA"]) };

      //atualizando o model - entity
      TryUpdateModel(cadastro, new string[] {"DAT_CADASTRO", "DSC_NOME", "DAT_NASCIMENTO", "NUM_IDENTIDADE", "NUM_CPF", "DSC_ENDERECO",
        "NOM_BAIRRO", "NOM_CIDADE", "SEQ_UF", "NUM_CEP", "NUM_TELEFONE_CASA", "NUM_TELEFONE_CELULAR", "NUM_TELEFONE_TRABALHO",
        "NUM_TELEFONE_FAX", "DSC_EMAIL", "NOM_PAI", "NOM_MAE", "DSC_OBSERVACAO", "NOM_ARQUIVO_FOTO", "DSC_SITUACAO_CADASTRO", 
        "FLG_CADASTRO_CBK", "DSC_SITUACAO_CADASTRO_CBK", "DAT_CADASTRO_CBK", "FLG_CONTATO_ACADEMIA", "SEQ_ACADEMIA"}, formCadastro.ToValueProvider());

      //Atualiza valores das FKs
      entities.AttachTo("UF", novaUF);
      entities.AttachTo("ACADEMIA", novaAcademia);

      cadastro.UF = novaUF;
      cadastro.ACADEMIA = novaAcademia;

      //se tudo estiver certo, o modelo é atualizado
      if (ModelState.IsValid){
        entities.SaveChanges();
        return RedirectToAction("Index");
      }

      return View(cadastro);
    }

    [HttpPost]
    public RedirectToRouteResult Apagar(FormCollection formApagar){
      var cadastroId = Int32.Parse(formApagar["SEQ_CADASTRO"]);
      var cadastro = entities.CADASTRO.First(c => c.SEQ_CADASTRO == cadastroId);
      entities.DeleteObject(cadastro);
      entities.SaveChanges();
      return RedirectToAction("Index");
    }
  }
}